package com.dferreira.languagesteach;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import com.dferreira.languagesteach.constants.Constants;
import com.dferreira.languagesteach.utils.ApplicationState;
import com.google.gson.Gson;

/**
 * Created by dferreira on 5/31/14.
 * for LanguagesTeach
 */
public class LanguagesTeachApplication extends Application {
    private static ApplicationState applicationState;
    private static Context context;

    /**
     * @return true if there exists already a subjectPath saved false otherwise
     */
    private Boolean existAnySubjectPathSaved() {
        String globalStateStr = null;
        SharedPreferences settings;

        try {
            settings = this.getSharedPreferences(Constants.LAST_SESSION_STORAGE, 0);
            globalStateStr = settings.getString(Constants.LAST_SESSION_KEY, null);
        } catch (Exception ignored) {
        }
        return globalStateStr != null;
    }

    /**
     * @return lastSubject path saved on sharedPreferences
     */
    public ApplicationState getLastSubjectPath() {
        Gson gson;
        ApplicationState applicationState = null;
        String globalStateStr;
        SharedPreferences settings;

        try {
            gson = new Gson();
            settings = this.getSharedPreferences(Constants.LAST_SESSION_STORAGE, 0);
            globalStateStr = settings.getString(Constants.LAST_SESSION_KEY, null);
            if (globalStateStr != null) {
                applicationState = gson.fromJson(globalStateStr, ApplicationState.class);
            }
        } catch (Exception ignored) {
        }
        return applicationState;
    }

    /**
     * Saved the subject path on sharedPreferences
     */
    public static void saveSubjectPath() {
        Gson gson;
        String globalStateStr;
        SharedPreferences settings;
        SharedPreferences.Editor editor;
        try {
            if (applicationState != null) {
                gson = new Gson();
                globalStateStr = gson.toJson(applicationState);
            } else {
                globalStateStr = null;
            }
            settings = context.getSharedPreferences(Constants.LAST_SESSION_STORAGE, 0);
            editor = settings.edit();

            editor.putString(Constants.LAST_SESSION_KEY, globalStateStr);
            editor.commit();
        } catch (Exception ignored) {
        }

    }


    /**
     *
     */
    @Override
    public final void onCreate() {
        applicationState = new ApplicationState();
        context = this;
        super.onCreate();
    }

    /**
     * @return
     */
    public static ApplicationState getApplicationState() {
        return applicationState;
    }

    /**
     *
     * @return
     */
    public static Context getContext() {
        return context;
    }
}
